package com.itboye.sunsun.luntan;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.sunsun.MainHomeActivity;
import com.itboye.sunsun.adapter.LuntanZhiKanLouZhuAdapter;
import com.itboye.sunsun.adapter.TieziCommentNewAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LunTanCommontBean;
import com.itboye.sunsun.beans.TieZiBeanNew;
import com.itboye.sunsun.beans.TieZiBeanNew.TieZiCommentItem;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.FaceInputView;
import com.itboye.sunsun.custome.FaceInputView.Face;
import com.itboye.sunsun.custome.FaceInputView.OnFaceClickListener;
import com.itboye.sunsun.custome.RoundImage;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.dialog.WaitDialog;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.person.ui.NewsDetailShareFragment;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.uesrinfo.TieZiQuanXianManager;
import com.itboye.sunsun.utils.CameraPopupWindow;
import com.itboye.sunsun.utils.DateLineParse;
import com.itboye.sunsun.utils.DensityUtil;
import com.itboye.sunsun.utils.ImageCompress;
import com.itboye.sunsun.utils.PhotoSelectFragment;
import com.itboye.sunsun.utils.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.SoftwareUtil;
import com.itboye.sunsun.utils.Spanned2String;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.utils.XPicasso;
import com.itboye.sunsun.volley.ImageCompressAndUpload;
import com.itboye.sunsun.volley.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.String2Spanned;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.umeng.socialize.utils.Log;

import static com.itboye.sunsun.constants.NetPublicConstant.WEB_URL;

//

public class TieZiDetailActivity extends BaseActivity implements
		IXListViewListener {

	XListView xlistview;
	ImageView shoucang, back;

	// LunTanItemBean lunTanItemBean;
	// BaseExpandableListAdapter adapter;
	LunTanCommontBean commontList = new LunTanCommontBean();
	private int pageNum = 1;
	ViewGroup bottom;
	EditText input;
	View headerView;
	ViewGroup imgContainer;
	String fid;
	String tid;
	View addImg;
	View addEmoj;
	Integer gentiePosition = null;
	LinearLayout selectImgContainer;
	// boolean isGentie=true;
	WaitDialog waitDialog;
	View jubao;
	String pid = "";
	String beiJuBaoId = "";
	String beiJuBaoUserName = "";

	String authorId = "";

	ImageView share;
	View jiajing;
	View zhiding;

	int only = 0;
	int isBut = 0;
	View delete;
	FaceInputView faceInputView;
	HorizontalScrollView horizontalScrollView;
	// 点赞
	private String isLove;
	protected String content;
	private String title;
	boolean isLoadMore = false;
	RelativeLayout re_two;
	//
	PopupWindow popupWindow;
	ImageView imgpupowind;
	public static Activity activity;
	ArrayList<TieZiBeanNew.TieZiCommentItem> arrayListComment = new ArrayList<TieZiBeanNew.TieZiCommentItem>();
	ArrayList<TieZiBeanNew.TieZiCommentItem> louzhulist = new ArrayList<TieZiBeanNew.TieZiCommentItem>();

	private TieziCommentNewAdapter commentNewAdapter;
	TextView txt_dianzancount;
	LuntanZhiKanLouZhuAdapter kanLouZhuAdapter;

	private boolean isButton = true;
	private View popuview;
	public static int WIDTH = 0;
	int isfavStatus = 0;
	LinearLayout image;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_tiezi_xiangqing);
		activity = this;
		WIDTH = getWindowManager().getDefaultDisplay().getWidth();
		popuview = LayoutInflater.from(App.ctx).inflate(R.layout.wo_item, null);
		txt_collection = (TextView) popuview.findViewById(R.id.txt_collection);
		IntentFilter filter2 = new IntentFilter("changegroup");
		registerReceiver(broadcastReceiver2, filter2);
		showProgressDialog("数据加载中，请稍后", true);
		xlistview.setXListViewListener(this);
		xlistview.setPullRefreshEnable(true);
		xlistview.setPullLoadEnable(true);
		setStatusBarColor(R.color.home_blue);

		fid = getIntent().getStringExtra("fid");
		tid = getIntent().getStringExtra("tid");
		System.out
				.println("<><><><>><><>><<>" + tid + "\n<><><><><><><>" + fid);
		commentNewAdapter = new TieziCommentNewAdapter(arrayListComment,
				onclicklister, TieZiDetailActivity.this);

		xlistview.setAdapter(commentNewAdapter);

		authorId = getIntent().getStringExtra("author_id");
		shoucang.setEnabled(false);
		headerView = getLayoutInflater().inflate(
				R.layout.item_tiezi_detail_headerview, null);
		re_two = (RelativeLayout) headerView.findViewById(R.id.re_two);
		re_two.setOnClickListener(onclicklister);
		image = (LinearLayout) headerView.findViewById(R.id.image);
		txt_dianzancount = (TextView) headerView
				.findViewById(R.id.txt_dianzancount);
		xlistview.addHeaderView(headerView);

		jiajing = headerView.findViewById(R.id.jiajing);
		zhiding = headerView.findViewById(R.id.zhiding);
		jiajing.setTag(false);
		zhiding.setTag(false);
		input.setOnClickListener(onclicklister);
		imgpupowind = (ImageView) findViewById(R.id.imgpupowind);
		imgpupowind.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onPupoWindow(v);
				// ByAlert.alert("Toaset");
			}
		});

		imgContainer = (ViewGroup) headerView.findViewById(R.id.imgContainer);
		headerView.findViewById(R.id.zan).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// onBBsPraiseClick(v);
						LoginController.onBBSPraiseClick(
								TieZiDetailActivity.this, null);
					}
				});

		delete = headerView.findViewById(R.id.delete);
		getYuanTieInfo();
		initListener();
	}

	public void initListener() {
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				finish();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				boolean isOpen = imm.isActive();
				// isOpen若返回true，则表示输入法打开
				System.out.println("<>>>>>>>>>>>>>>>>>>>" + isOpen);
			}
		});
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			huifu();
		};
	};
	protected int size;

	BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			size = intent.getIntExtra("size", 0);
			huifu();
			getYuanTieInfo();
			// getYuanTieInfoo();
		};
	};
	protected String favStatus;
	protected TieZiCommentItem detailBean;

	public void getYuanTieInfo() {

		MyJsonRequest.Builder<TieZiBeanNew.TieZiCommentItem> builder = new MyJsonRequest.Builder<TieZiBeanNew.TieZiCommentItem>()
				.apiVer("100")
				.typeKey("BY_ForumPost_threaddetail")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(
						new XRequestListener<TieZiBeanNew.TieZiCommentItem>() {

							@Override
							public void onResponse(
									TieZiBeanNew.TieZiCommentItem bean) {
								detailBean = bean;
								isLove = bean.getIsLove();
								if (Integer.parseInt(isLove) == 1) {
									((ImageView) headerView
											.findViewById(R.id.zan))
											.setImageResource(R.drawable.dianzan);
								} else {
									((ImageView) headerView
											.findViewById(R.id.zan))
											.setImageResource(R.drawable.dianzan_unselect);
								}

								setImageInfo(bean);
								addHeaderImageAndContent(bean);
								addYuanTieUserInfo(bean);
								getCommentContent(tid, only);
								// fid = bean.getFid();
								//
								//
								// content = bean.getMessage();

								delete.setVisibility(View.GONE);

								try {
									closeProgressDialog();
								} catch (Exception e) {
									// TODO: handle exception
								}
								// pullDown();
							}

						}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<TieZiBeanNew.TieZiCommentItem> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	protected void setImageInfo(TieZiCommentItem bean) {
		// TODO Auto-generated method stub
		if (bean != null) {
			if (bean.getImg() != null) {
				if (bean.getImg().size() > 0) {
					for (int i = 0; i < bean.getImg().size(); i++) {
						String imgId = bean.getImg().get(i);
						if (detailBean.getMessage().contains(
								"{pic" + imgId + "}")) {
						} else {
							ImageView imageView = new ImageView(
									getApplicationContext());
							LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
									getWindowManager().getDefaultDisplay()
											.getWidth(),
									LinearLayout.LayoutParams.WRAP_CONTENT);
							layoutParams.setMargins(0, 5, 0, 5);
							imageView.setLayoutParams(layoutParams);
							imageView.setScaleType(ScaleType.FIT_XY);
							image.addView(imageView, layoutParams);
							XPicasso.loadImage(TieZiDetailActivity.this,
									imageView, NetPublicConstant.IMAGE_URL
											+ imgId);
						}
					}
				}
			}
		}
	}

	public void getYuanTieInfoo() {

		MyJsonRequest.Builder<TieZiBeanNew.TieZiCommentItem> builder = new MyJsonRequest.Builder<TieZiBeanNew.TieZiCommentItem>()
				.apiVer("100")
				.typeKey("BY_ForumPost_threaddetail")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))

				.requestListener(
						new XRequestListener<TieZiBeanNew.TieZiCommentItem>() {

							@Override
							public void onResponse(
									TieZiBeanNew.TieZiCommentItem bean) {
								// System.out.println(bean.);
								isLove = bean.getIsLove();
								if (Integer.parseInt(isLove) == 1) {
									((ImageView) headerView
											.findViewById(R.id.zan))
											.setImageResource(R.drawable.dianzan);
								} else {
									((ImageView) headerView
											.findViewById(R.id.zan))
											.setImageResource(R.drawable.dianzan_unselect);
								}

								addHeaderImageAndContent(bean);
								addYuanTieUserInfo(bean);
								// fid = bean.getFid();
								//
								//
								// content = bean.getMessage();

								delete.setVisibility(View.GONE);

								try {
									closeProgressDialog();
								} catch (Exception e) {
									// TODO: handle exception
								}
								// pullDown();
							}

						}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<TieZiBeanNew.TieZiCommentItem> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	protected void getCommentContent(String tid2, final int only) {
		// TODO Auto-generated method stub
		MyJsonRequest.Builder<TieZiBeanNew> builder = new MyJsonRequest.Builder<TieZiBeanNew>()
				.apiVer("100").typeKey("BY_ForumPost_cardreply")
				.param("tid", tid2).param("curpage", pageNum)
				.param("pagesize", 10).param("only", only)
				.requestListener(new XRequestListener<TieZiBeanNew>() {

					@Override
					public void onResponse(TieZiBeanNew bean) {
						txt_commentCount.setText(bean.getCount());
						if (pageNum == 1) {
							arrayListComment.clear();
						}
						arrayListComment.addAll(bean.getList());
						commentNewAdapter.notifyDataSetChanged();
						if (only == 1) {
							louzhulist.addAll(bean.getList());
							kanLouZhuAdapter.notifyDataSetChanged();
						}
						stopLoad();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
						// pullDown();
					}

				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<TieZiBeanNew> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	// 输入表情需要
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};
	private TextView txt_commentCount;

	/*
	 * 
	 * 楼主信息
	 */
	private void addYuanTieUserInfo(TieZiBeanNew.TieZiCommentItem bean) {
		// TODO Auto-generated method stub
		String author = bean.getAuthor();// 作者
		String dateLine = bean.getDateline();// 发帖时间
		String head = bean.getHead();// 用户头像 ///
										// Uploads/UserPicture/2015-10-24/562b2e6467438.png
		String fName = bean.getName();// 板块名字
		String title = bean.getSubject();// 帖子标题
		String liulanliang = bean.getViews();// 浏览量
		String commentCount = bean.getReplies();// 评论数
		RoundImage headImage = (RoundImage) headerView.findViewById(R.id.head);
		TextView name = (TextView) headerView.findViewById(R.id.name);
		TextView date = (TextView) headerView.findViewById(R.id.txt_time);
		TextView txt_liulanliang = (TextView) headerView
				.findViewById(R.id.txt_liulanliang);

		TextView txt_fName = (TextView) headerView.findViewById(R.id.fname);
		TextView txt_title = (TextView) headerView.findViewById(R.id.txt_title);

		RelativeLayout re_jubao = (RelativeLayout) headerView
				.findViewById(R.id.re_jubao);

		final TextView txt_jubao = (TextView) headerView
				.findViewById(R.id.txt_jubao);
		txt_commentCount = (TextView) headerView
				.findViewById(R.id.txt_commentcount);
		txt_commentCount = (TextView) headerView
				.findViewById(R.id.txt_commentcount);// 评论数量
		txt_commentCount.setText(commentCount);

		XImageLoader.load(head, headImage);
		txt_title.setText(title);
		txt_fName.setText(fName);
		name.setText(author);
		if (dateLine != null)
			date.setText(DateLineParse.getParseTime(dateLine));
		txt_liulanliang.setText(liulanliang);
		initView();

		re_jubao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				LoginController.onJuBao(TieZiDetailActivity.this, null);

			}
		});
	}

	protected NewsDetailShareFragment fragment;

	private void initView() {

		addEmoj.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// ByAlert.alert(SoftwareUtil.isImeShow(getApplicationContext())+"");
				// SoftwareUtil.showOrHideSoftware(input, App.ctx, false);
				v.setSelected(!v.isSelected());
				if (faceInputView == null) {
					faceInputView = new FaceInputView(getApplicationContext());
					bottom.addView(faceInputView);
					faceInputView.setOnClickListener(new FaceInputListenr());
				}

				if (selectImgContainer != null) {
					isShowImage = true;
					showOrHideFace();
				}
				showOrHideAddImage();
				hideSoftInput();
			}
		});
		input.setFocusable(true);
		input.requestFocus();
		addImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				SoftwareUtil.showOrHideSoftware(input, App.ctx, false);
				if (selectImgContainer == null) {
					horizontalScrollView = (HorizontalScrollView) getLayoutInflater()
							.inflate(R.layout.item_pinglun_img_select, bottom,
									false);
					bottom.addView(horizontalScrollView);
					selectImgContainer = (LinearLayout) horizontalScrollView
							.getChildAt(0);

					selectImgContainer.getChildAt(0).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									mCameraPopupWindow = new CameraPopupWindow(
											TieZiDetailActivity.this,
											onclicklister);
									mCameraPopupWindow.showAtLocation(
											selectImgContainer.getChildAt(0),
											Gravity.BOTTOM
													| Gravity.CENTER_HORIZONTAL,
											0, 0);

								}
							});

				}

				if (faceInputView != null) {
					isFaceShow = true;
					showOrHideFace();
				}
				showOrHideAddImage();
				hideSoftInput();
			}

		});
		//
		findViewById(R.id.send).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(input.getText().toString())) {
					Toast.makeText(App.ctx, "请输入跟帖内容", 0).show();
					return;
				}
				LoginController.onBBSCommentClick(TieZiDetailActivity.this,
						null);

			}
		});
		//

	}

	private CameraPopupWindow mCameraPopupWindow;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				if (selectImgContainer.getChildCount() > 6) {
					Toast.makeText(TieZiDetailActivity.this, "最多上传6张照片", 0)
							.show();
					mCameraPopupWindow.dismiss();
					return;
				}
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {

					/**
					 * 打开照相机
					 */
					picture_name = android.text.format.DateFormat.format(
							"yyyyMMdd_hhmmss",
							Calendar.getInstance(Locale.CHINA))
							+ ".jpg";
					File file = new File("/sdcard/Image/");
					file.mkdirs();// 创建文件夹
					fileName = "/sdcard/Image/" + picture_name;
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(fileName)));
					startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);

				} else {
					Toast.makeText(TieZiDetailActivity.this, "请确认已经插入SD卡", 0)
							.show();
				}
				break;
			case R.id.pick_image:
				new PhotoSelectFragment(photoListenr,
						6 - selectImgContainer.getChildCount() + 1).show(
						getSupportFragmentManager(), null);

				mCameraPopupWindow.dismiss();
				break;
			case R.id.img:
				break;
			case R.id.re_collection:
				LoginController.onBBSCollectClick(TieZiDetailActivity.this,
						null);
				break;
			case R.id.re_comment:// 用户回复上面的回复
				pid = view.getTag(R.id.tag_second) + "";
				gentiePosition = Integer.parseInt(view.getTag() + "");
				input.setHint("回复 " + view.getTag(R.id.tag_first) + ":");
				addImg.setVisibility(View.GONE);
				SoftwareUtil.showOrHideSoftware(input,
						TieZiDetailActivity.this, true);
				// show(true, v);
				break;
			case R.id.re_two:// 帖子上面的回复
				addImg.setVisibility(View.VISIBLE);
				input.setHint("评论 " + author + ":");
				SoftwareUtil.showOrHideSoftware(input,
						TieZiDetailActivity.this, true);

				break;
			case R.id.input:
				if (isFaceShow) {
					showOrHideFace();
				}
				if (isShowImage) {
					showOrHideAddImage();
				}
				break;

			default:
				break;
			}
		}
	};
	private boolean isFaceShow;
	private boolean isShowImage;

	private void showOrHideFace() {
		if (faceInputView != null) {
			if (isFaceShow) {
				faceInputView.setVisibility(View.GONE);
			} else {
				faceInputView.setVisibility(View.VISIBLE);
			}
			isFaceShow = !isFaceShow;
		}
	}

	private void showOrHideAddImage() {
		if (selectImgContainer != null) {
			if (isShowImage) {
				((View) selectImgContainer.getParent())
						.setVisibility(View.GONE);
			} else {
				((View) selectImgContainer.getParent())
						.setVisibility(View.VISIBLE);
			}
			isShowImage = !isShowImage;
		}
	}

	private String picture_name;
	private String fileName;
	private View v;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
			if (resultCode == RESULT_OK) {
				Bitmap bit = BitmapFactory.decodeFile(fileName);
				int degree = ImageCompress.readPictureDegree(fileName);
				if (degree <= 0) {
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				saveImage(bit, new File(fileName));
			} else {
				Toast.makeText(this, "拍照取消", 0).show();
			}
			mCameraPopupWindow.dismiss();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveImage(Bitmap data, File file) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(fileName);
			data.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			v = LayoutInflater.from(getApplicationContext()).inflate(
					R.layout.item_fabiao_tiezi_image_select, null);

			v.setLayoutParams(new LayoutParams(DensityUtil.dip2px(80),
					LayoutParams.MATCH_PARENT));
			((ImageView) v.findViewById(R.id.img)).setImageBitmap(data);
			v.setTag(fileName);
			selectImgContainer.addView(v,
					selectImgContainer.getChildCount() - 1);

			v.findViewById(R.id.del).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View vvv) {
					selectImgContainer.removeView(v);
					arrayList.remove(v);
				}
			});
			arrayList.add(v);
		} catch (Exception e) {
			Log.e("error", e.getMessage());
		}
	}

	public void onJuBaoCLick() {
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("100")
				.typeKey("BY_CoreReport_bbsReport")
				.param("tid", tid)
				.param("fid", fid)
				.param("pid", pid)
				.param("uid", beiJuBaoId)
				.param("username", beiJuBaoUserName)
				.param("op_uid",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String bean) {

						Toast.makeText(getApplicationContext(), "举报成功", 1)
								.show();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						ByAlert.alert(msg);
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void onBBsPraiseClick() {
		if (isLove.equals("1")) {
			ByAlert.alert("已经点赞过了哦!");
			return;
		}
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("101")
				.typeKey("BY_ForumThread_like")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						/***
						 * 当islove为0时是已经点赞成功了的否则是点赞过了的无需点赞
						 */
						ByAlert.alert(orderBean);
						int count = Integer.parseInt(txt_dianzancount.getText()
								.toString());
						count = count + 1;
						txt_dianzancount.setText(count + "");
						((ImageView) headerView.findViewById(R.id.zan))
								.setImageResource(R.drawable.dianzan);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(getApplicationContext(), msg, 1).show();
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	ArrayList<View> arrayList = new ArrayList<>();

	// 收藏
	public void onBBsCollectClick() {
		// TODO Auto-generated method stub

		popupWindow.dismiss();

		if (isfavStatus == 0) {
			isfavStatus = 1;
			if (favStatus != null) {
				if (!favStatus.equals("0")) {
					ByAlert.alert("已经收藏了哦！");
					return;
				}
			}

		}

		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("100")
				.typeKey("BY_ForumThread_favorites")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.param("favorite_value", isfavStatus)
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						ByAlert.alert("收藏成功！");

						if (favStatus.equals("0")) {
							txt_collection.setText("已收藏");
						} else {
							txt_collection.setText("收藏");
						}
						// favStatus = "1";
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// v.setEnabled(true);
						ByAlert.alert(msg);
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	PhotoSelectListener photoListenr = new PhotoSelectListener() {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {

				Bitmap bit = BitmapFactory.decodeFile(string);
				int degree = ImageCompress.readPictureDegree(string);
				if (degree <= 0) {
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				FileOutputStream b = null;
				try {
					b = new FileOutputStream(string);
					bit.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// saveImage(bit, new File(string));

				v = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.item_fabiao_tiezi_image_select, null);

				v.setLayoutParams(new LayoutParams(DensityUtil.dip2px(80),
						LayoutParams.MATCH_PARENT));

				((ImageView) v.findViewById(R.id.img)).setImageBitmap(bit);
				// XImageLoader.load("file://" + string,
				// (ImageView) v.findViewById(R.id.img));
				v.setTag(string);
				selectImgContainer.addView(v,
						selectImgContainer.getChildCount() - 1);

				v.findViewById(R.id.del).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View vvv) {
								selectImgContainer.removeView(v);
								arrayList.remove(v);
							}
						});
				arrayList.add(v);

			}
		}
	};

	public void onCommentClick() {
		if (!TieZiQuanXianManager.canPublishMessage(fid)) {
			Toast.makeText(getApplicationContext(), "无权发帖", 1).show();
			return;
		}
		if (gentiePosition != null) {
			// 评论
			MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
					.apiVer("100")
					.typeKey("BY_ForumPost_replyPost")
					.param("tid", tid)
					.param("pid", pid)
					.param("author",
							(String) SPUtils.get(getApplicationContext(), null,
									SPContants.NICK, ""))
					.param("author_id",
							(String) SPUtils.get(getApplicationContext(), null,
									SPContants.USER_ID, ""))
					.param("comment", Spanned2String.parse(input.getText()))
					.requestListener(new XRequestListener<String>() {

						@Override
						public void onResponse(String orderBean) {
							input.setText(null);
							Toast.makeText(getApplicationContext(), "评论成功", 1)
									.show();
							pageNum = 1;
							getCommentContent(tid, only);
							// getCommentContentLou(tid);
							// pullDown();
							huifu();
						}
					}).errorListener(new XErrorListener() {

						@Override
						public void onErrorResponse(Exception exception,
								int code, String msg) {
							Toast.makeText(getApplicationContext(), "评论失败", 1)
									.show();
						}
					});

			MyJsonRequest<String> request = builder.build();
			HttpRequest.getDefaultRequestQueue().add(request);
		} else {
			if (selectImgContainer == null
					|| selectImgContainer.getChildCount() == 1) {
				sendToServer(null);
				return;
			}
			// 回帖
			if (waitDialog == null) {
				waitDialog = new WaitDialog();
			}
			waitDialog.show(getSupportFragmentManager(), null);
			final Toast toast = Toast.makeText(getApplicationContext(),
					"图片上传失败", 1);
			final List<String> uploadedUrl = new ArrayList<>();
			for (int i = 0; i < selectImgContainer.getChildCount() - 1; i++) {

				ImageCompressAndUpload.getInstance().execute(
						(String) selectImgContainer.getChildAt(i).getTag(),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);

								if (uploadedUrl.size() == selectImgContainer
										.getChildCount() - 1) {
									if (waitDialog != null) {
										waitDialog.dismiss();
									}

									sendToServer(uploadedUrl);
								}
							}

							@Override
							public void OnError(String resultData) {
								if (waitDialog != null) {
									waitDialog.dismiss();
								}

								toast.show();
							}
						});

			}

		}
	}

	boolean isAddHeader = false;
	private int gentieSize;
	private String html;
	private TextView textVieConten;
	private String author;
	private TextView txt_collection;

	// private NetworkImageGetter mImageGetter;

	// 回帖
	protected void sendToServer(List<String> uploadedUrl) {
		MyJsonRequest.Builder<Object> builder = new MyJsonRequest.Builder<Object>()
				.apiVer("100")
				.typeKey("BY_ForumPost_reply")
				.param("fid", fid)
				.param("tid", tid)
				.param("author",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.NICK, ""))
				.param("author_id",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.param("message", Spanned2String.parse(input.getText()))

				.requestListener(new XRequestListener<Object>() {

					@Override
					public void onResponse(Object orderBean) {

						// GenTieItemBean bean = new GenTieItemBean();
						// bean.setDateline(System.currentTimeMillis() + "");
						// bean.setMessage(input.getText());
						// bean.setSubject(input.getText());
						// commontList.getList().add(bean);
						//
						// adapter.notifyDataSetChanged();
						Toast.makeText(getApplicationContext(), "回帖成功", 1)
								.show();
						pageNum = 1;
						getCommentContent(tid, only);
						// pullDown();
						for (int i = 0; i < arrayList.size(); i++) {

							selectImgContainer.removeView(arrayList.get(i));
						}
						input.setText(null);
						((View) selectImgContainer.getParent())
								.setVisibility(View.GONE);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(getApplicationContext(), "回帖失败", 1)
								.show();
					}
				});

		if (uploadedUrl != null && uploadedUrl.size() > 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(uploadedUrl.get(0));
			for (int i = 1; i < uploadedUrl.size(); i++) {
				sb.append(",").append(uploadedUrl.get(i));
			}

			builder.param("attachments", sb.toString());

		}
		MyJsonRequest<Object> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private class FaceInputListenr implements OnFaceClickListener {

		@Override
		public void selectedFace(Face face) {
			int id = face.faceId;
			if (id == R.drawable.ic_face_delete_normal)// 删除按钮
			{
				int index = input.getSelectionStart();
				if (index == 0)
					return;
				Editable editable = input.getText();
				editable.delete(index - 1, index);// 删除最后一个字符或表情
			} else {
				input.append(Html.fromHtml("<img src='" + id + "'/>",
						imageGetter, null));// 添加表情
			}
		}

	}

	protected void pullUp() {
		System.out.println(fid + ":" + tid + ":" + pageNum);
		MyJsonRequest.Builder<LunTanCommontBean> builder = new MyJsonRequest.Builder<LunTanCommontBean>()
				.param("fid", fid).param("tid", tid).apiVer("100")
				.param("curpage", "" + pageNum)
				.typeKey("BY_ForumPost_threaddetail")
				.requestListener(new XRequestListener<LunTanCommontBean>() {

					@Override
					public void onResponse(LunTanCommontBean orderBean) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						// updateCommentList(orderBean);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
					}
				});

		MyJsonRequest<LunTanCommontBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	protected void addHeaderImageAndContent(
			TieZiBeanNew.TieZiCommentItem genTieItemBean) {
		html = genTieItemBean.getMessage();
		favStatus = genTieItemBean.getFavStatus();// 判断收藏的状态
		if (favStatus != null)
			txt_collection.setText(favStatus.equals("0") ? "收藏" : "已收藏");
		author = genTieItemBean.getAuthor();// 该贴的作者
		authorId = genTieItemBean.getAuthorId();// 该贴的作者id

		beiJuBaoId = genTieItemBean.getAuthorId();
		beiJuBaoUserName = genTieItemBean.getAuthor();
		pid = genTieItemBean.getPid();
		txt_dianzancount.setText(genTieItemBean.getLikes());
		System.out.println("content数据" + html);
		textVieConten = ((TextView) headerView.findViewById(R.id.content));
		textVieConten.setText(String2Spanned.parsed(html));
		textVieConten.setMovementMethod(LinkMovementMethod.getInstance());

	}

	private void pullDown() {
		MyJsonRequest.Builder<LunTanCommontBean> builder = new MyJsonRequest.Builder<LunTanCommontBean>()
				.param("fid", fid).param("tid", tid).apiVer("100")
				.param("curpage", "" + pageNum)
				.typeKey("BY_ForumPost_threaddetail")
				.requestListener(new XRequestListener<LunTanCommontBean>() {

					@Override
					public void onResponse(LunTanCommontBean bean) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						gentieSize = bean.getCount();
						if (bean.getCount() > 0 && bean.getList() != null) {
							try {

								pid = bean.getList().get(0).getPid();
								beiJuBaoId = bean.getList().get(0)
										.getAuthorId();
								beiJuBaoUserName = bean.getList().get(0)
										.getUserInfo().getUsername();
							} catch (Exception e) {
							}
							commontList.getList().clear();
							if (isAddHeader == false) {
								// addHeaderImageAndContent(bean.getList().get(0));
								isAddHeader = true;
							}
							bean.getList().remove(0);
							// updateCommentList(bean);

						}
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<LunTanCommontBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	public void onComment(int gentiePosition) {
		this.gentiePosition = gentiePosition;
		input.setHint("评论");
		addImg.setVisibility(View.GONE);
	}

	public void huifu() {
		gentiePosition = null;
		input.setHint("回复");
		addImg.setVisibility(View.VISIBLE);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (addEmoj.isSelected()) {
				faceInputView.setVisibility(View.GONE);
				addEmoj.setSelected(false);
				return true;
			}

			if (addImg.isSelected()) {
				horizontalScrollView.setVisibility(View.GONE);
				addImg.setSelected(false);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// unregisterReceiver(broadcastReceiver);
		unregisterReceiver(broadcastReceiver2);
	}

	public void onPupoWindow(View view) {

		final TextView tvlouzhu = (TextView) popuview
				.findViewById(R.id.tvlouzhu);

		RelativeLayout relayoutShare = (RelativeLayout) popuview
				.findViewById(R.id.relayoutShare);
		RelativeLayout re_collection = (RelativeLayout) popuview
				.findViewById(R.id.re_collection);

		re_collection.setOnClickListener(onclicklister);
		RelativeLayout louyouLouZhu = (RelativeLayout) popuview
				.findViewById(R.id.louyouLouZhu);

		tvlouzhu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isBut == 0) {
					only = 1;
					isBut = 1;

					tvlouzhu.setText("查看全部");
					getYuanTieInfo();
					kanLouZhuAdapter = new LuntanZhiKanLouZhuAdapter(
							louzhulist, onclicklister, activity);
					xlistview.setAdapter(kanLouZhuAdapter);
				} else if (isBut == 1) {
					only = 2;
					isBut = 0;
					tvlouzhu.setText("只看楼主");
					getYuanTieInfo();
					commentNewAdapter = new TieziCommentNewAdapter(
							arrayListComment, onclicklister, activity);
					xlistview.setAdapter(commentNewAdapter);

				}
			}
		});
		/**
		 * 楼主点击http://sunsun.itboye.com/index.php/Webview/HomeView/viewvideo/id/
		 * 931
		 * **/
		louyouLouZhu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (only == 1) {
					tvlouzhu.setText("只看楼主");
					popupWindow.dismiss();
					getYuanTieInfo();
				} else {
					tvlouzhu.setText("查看全部");
					popupWindow.dismiss();
					getYuanTieInfo();
				}
			}
		});
		relayoutShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				fragment = new NewsDetailShareFragment();
				Bundle args = new Bundle();
				args.putString("content", getString(R.string.download));
				args.putString("title", getString(R.string.download));
				fragment.setArguments(args);
				fragment.show(getSupportFragmentManager(),
						WEB_URL + "/User/download?type=sunsunhome");
			}
		});
		popupWindow = new PopupWindow(popuview,
				(int) (MainHomeActivity.screenWidth / 2.5),
				LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAsDropDown(view);
	}

	/**
	 * 加载网络图片异步类
	 * 
	 * @author Susie
	 */
	@SuppressWarnings("unused")
	private final class AsyncLoadNetworkPic extends
			AsyncTask<String, Integer, Void> {

		@Override
		protected Void doInBackground(String... params) {
			// 加载网络图片
			loadNetPic(params);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// 当执行完成后再次为其设置一次
			// textVieConten.setText(Html.fromHtml(html, mImageGetter, null));
		}

		/** 加载网络图片 */
		private void loadNetPic(String... params) {
			String path = params[0];
			path = NetPublicConstant.IMAGE_URL+"13695";
			File file = new File(Environment.getExternalStorageDirectory(),
					picName);

			InputStream in = null;

			FileOutputStream out = null;

			try {
				URL url = new URL(path);

				HttpURLConnection connUrl = (HttpURLConnection) url
						.openConnection();

				connUrl.setConnectTimeout(5000);

				connUrl.setRequestMethod("POST");

				if (connUrl.getResponseCode() == 200) {

					in = connUrl.getInputStream();

					out = new FileOutputStream(file);

					byte[] buffer = new byte[1024];

					int len;

					while ((len = in.read(buffer)) != -1) {
						out.write(buffer, 0, len);
					}
				} else {
					Log.i("tag", connUrl.getResponseCode() + "");
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {

				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/** 网络图片name */
	private String picName = "networkPic.jpg";

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		pageNum = 1;
		getCommentContent(tid, only);
		// getCommentContentLou(tid);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		pageNum++;
		getCommentContent(tid, only);
		// getCommentContentLou(tid);
	}

	public void stopLoad() {
		xlistview.stopLoadMore();
		xlistview.stopRefresh();
	}

	private void hideSoftInput() {
		// 1.得到InputMethodManager对象
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 2.调用hideSoftInputFromWindow方法隐藏软键盘
		imm.hideSoftInputFromWindow(input.getWindowToken(), 0); // 强制隐藏键盘
	}

}
